package com.wang.interceptors;

import com.google.common.base.Strings;
import com.mysql.cj.util.StringUtils;
import com.wang.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenUtil tokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
        // 登录效验:查看请求中是否存在token，如果不存在直接跳转到登陆页面
        String token = request.getHeader("Authorization");
        String userName =  token!=null ? tokenUtil.authToken(token):null;
        log.info("preHandle , token:" + token+", userName:"+userName);
        if (userName == null ) {
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println("{\"code\":5000,\"msg\":\"请先登录\"}");
            return false;
        }
        return true;
    }
}
